import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/layout/Layout.vue'
//解决重复点击报错bug
const VueRouterPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(to) {
    return VueRouterPush.call(this, to).catch(err => err);
}
const VueRouterReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function push(to) {
    return VueRouterReplace.call(this, to).catch(err => err);
}

Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
  },
  {
    path: '/',
    component: Layout,
    name:'LayOut',
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/Home.vue'),
        meta: { title: '首页' }
      },
      {
        path: 'user',
        redirect: '/user/list',
        name: 'User',
        component: () => import('@/views/user/index.vue'),
        meta: { title: '用户管理' },
        children: [
          {
            path: 'list',
            component: () => import('@/views/user/UserList'),
            meta: { title: '用户列表' }
          },
          {
            path: 'add',
            component: () => import('@/views/user/UserEdit'),
            meta: { title: '新增用户' }
          },
          {
            path: 'update/:id',
            name: 'updateUser',
            component: () => import('@/views/user/UserEdit'),
            meta: { title: '修改用户' },
            props: true
          }
        ]
      },
      {
        path: 'role',
        name: 'Role',
        component: () => import('@/views/user/role.vue'),
        meta: { title: '角色管理' }
      },
      {
        path: 'products',
        name: 'Products',
        component: () => import('@/views/products/index.vue'),
        meta: { title: '商品列表' }
      },
      {
        path: 'categories',
        name: 'Categories',
        component: () => import('@/views/products/categories.vue'),
        meta: { title: '分类管理' }
      },
      {
        path: 'orders',
        name: 'Orders',
        component: () => import('@/views/orders/index.vue'),
        meta: { title: '订单列表' }
      }
    ]
  }
]

const router = new VueRouter({
  mode:'history',
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoginnedIn = localStorage.getItem('isLoginnedIn')

  console.log('是否登录',isLoginnedIn);
  
  if (to.path === '/login') {
    if (isLoginnedIn) {
      next('/home')
    } else {
      next()
    }
  } else {
    if (isLoginnedIn) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
